package com.wlb365.financing.modules.schedule.job;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.wlb365.financing.modules.schedule.job.domain.OrgResult;
import com.wlb365.financing.modules.sys.entity.Dept;
import com.wlb365.financing.modules.sys.service.IDeptService;
import com.wlb365.sdk.client.SdkClient;
import com.wlb365.sdk.model.CommonRequest;
import com.wlb365.sdk.model.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 概述：定时同步兰格机构信息
 * </p>
 */
@Slf4j
@Component
public class LGOrgSyncJob extends QuartzJobBean {
    @Autowired
    private SdkClient sdkClient;

    @Autowired
    private IDeptService deptService;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) {
        //同步兰格机构信息
        CommonRequest request = new CommonRequest("fs.query.org-sync-org");
        Map<String, Object> param = new HashMap<>();

        request.setBizModel(param);
        CommonResponse response = sdkClient.execute(request);
        if ("000000".equals(response.getCode())) {
            JSONArray jsonArray = JSONUtil.parseArray(response.getData());
            List<OrgResult> orgResults = jsonArray.toList(OrgResult.class);
            orgResults.forEach(orgResult -> {
                Dept dept = new Dept();
                BeanUtil.copyProperties(orgResult,dept);
                dept.setParentId("0")
                        .setName(orgResult.getCompName())
                        .setType(Integer.valueOf(orgResult.getCompType()))
                        .setStatus(0)
                        .setSource("0");
                deptService.saveOrUpdate(dept);
            });

        }

    }
}